package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.common.utils.LuaConstants;
import com.hmdp.common.utils.RedisConstants;
import com.hmdp.common.utils.RedisIdWorker;
import com.hmdp.common.utils.UserHolder;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.*;

import static com.hmdp.common.utils.LuaConstants.*;
import static com.hmdp.common.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    //    @Resource
//    private IVoucherService voucherService;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("/lua/seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private BlockingQueue<VoucherOrder> blockingQueue = new ArrayBlockingQueue<>(1024 * 1024);
    private static final ExecutorService SAVE_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init() {
        SAVE_ORDER_EXECUTOR.submit(() -> {
//      处理订单异常
            while (true) {
                VoucherOrder voucherOrder = blockingQueue.take();
               placeOrder(voucherOrder);
            }
        });
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
////      判断时间是否符合要求
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//        LocalDateTime nowTime = LocalDateTime.now();
//
//        if (nowTime.isBefore(beginTime) || nowTime.isAfter(endTime)) {
////          时间不在可抢购的范围内
//            return Result.fail("不在抢购时间范围内");
//        }
        Long userId = UserHolder.getUser().getId();
        Long execute = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Arrays.asList(SECKILL_STOCK_KEY, SECKILL_ORDER_KEY),
                voucherId.toString(), userId.toString()
        );
        if (execute == null) {
            log.info("Lua脚本执行结果不符合预期");
            return Result.fail("服务器错误");
        }
        int returnValue = Integer.parseInt(execute.toString());
        if (returnValue != COMMIT_SUCCESS) {
//            错误列表
            switch (returnValue) {
                case LOWER_STOCK:
                    return Result.fail("库存不足");
                case DOUBLE_COMMIT:
                    return Result.fail("您已经抢购过");
            }
        }
//      todo 提交订单成功后逻辑
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(redisIdWorker.nextId("order:"));
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        blockingQueue.add(voucherOrder);

        return Result.ok(0);
    }


//    @Override
//    public Result seckillVoucher(Long voucherId) {
////      判断时间是否符合要求
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//        LocalDateTime nowTime = LocalDateTime.now();
//
//        if (nowTime.isBefore(beginTime) || nowTime.isAfter(endTime)) {
////          时间不在可抢购的范围内
//            return Result.fail("不在抢购时间范围内");
//        }
////        判断库存是否充足   (并发问题  超卖)
//        if (seckillVoucher.getStock() < 1) {
////            throw new RuntimeException();
//            return Result.fail("库存不足");
//        }
////        下单
//        Long userId = UserHolder.getUser().getId();
//        if (userId == null) {
//            throw new RuntimeException("登录信息异常");
//        }
////        synchronized (userId.toString().intern()) {
////        SimpleRedisLock redisLock = new SimpleRedisLock(SECKILL_VOUCHER, userId + "_" + voucherId, stringRedisTemplate);
//        RLock redisLock = redissonClient.getLock("lock:" + SECKILL_VOUCHER + userId + "_" + voucherId);
//        boolean tryLock = redisLock.tryLock(); // 默认情况下超时时间30s  获取失败不重试
////        获取锁
//        if (!tryLock) {
////            因为一人一单，有一个线程去请求之后，就不需要在重试了
//            return Result.fail("操作频繁");
//        }
//
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.placeOrder(voucherId, userId);
//        } finally {
//            redisLock.unlock();
//        }
////        }
//    }

    @Override
    @Transactional
    public void placeOrder(VoucherOrder order) {
        Long userId = order.getUserId();
        Long voucherId = order.getVoucherId();
        //      一个用户只能购买一张
        RLock lock = redissonClient.getLock(LOCK_VOUCHER_ORDER_KEY + voucherId);
        if (!lock.tryLock()) {
            log.info("来自阻塞队列:" + userId + "已有线程执行" + voucherId);
            return;
        }
        try {
            Long count = lambdaQuery()
                    .eq(VoucherOrder::getVoucherId, voucherId)
                    .eq(VoucherOrder::getUserId, userId)
                    .count();
            if (count > 0) {
                log.info("来自阻塞队列:" + userId + "已经购买过了" + voucherId);
                return;
            }

//          扣减库存   解决超卖问题 乐观锁
            boolean isSuccess = seckillVoucherService.lambdaUpdate()
                    .eq(SeckillVoucher::getVoucherId, voucherId)
                    .setSql("stock = stock - 1")
                    .gt(SeckillVoucher::getStock, 0)
                    .update();
            if (!isSuccess) {
                log.info("来自阻塞队列:" + userId + "的库存空了" + voucherId);
                return;
            }
//          生成订单
            VoucherOrder insertOrder = new VoucherOrder();
            insertOrder.setId(redisIdWorker.nextId("order:"));
            insertOrder.setUserId(UserHolder.getUser().getId());
            insertOrder.setVoucherId(voucherId);
            save(insertOrder);
        } finally {
            lock.unlock();
        }
    }
//    @Transactional
//    public Result placeOrder(Long voucherId, Long userId) {
////      一个用户只能购买一张
//        Long count = lambdaQuery()
//                .eq(VoucherOrder::getVoucherId, voucherId)
//                .eq(VoucherOrder::getUserId, userId)
//                .count();
//        if (count > 0) {
//            return Result.fail("您已经购买过了");
//        }
//
////          扣减库存   解决超卖问题 乐观锁
//        boolean isSuccess = seckillVoucherService.lambdaUpdate()
//                .eq(SeckillVoucher::getVoucherId, voucherId)
//                .setSql("stock = stock - 1")
//                .gt(SeckillVoucher::getStock, 0)
//                .update();
//        if (!isSuccess) {
//            return Result.fail("库存已经空空如也了");
//        }
////          生成订单
//        VoucherOrder insertOrder = new VoucherOrder();
//        insertOrder.setId(redisIdWorker.nextId("order:"));
//        insertOrder.setUserId(UserHolder.getUser().getId());
//        insertOrder.setVoucherId(voucherId);
//        save(insertOrder);
////          返回订单ID
//        return Result.ok(insertOrder.getId());
//    }
}
